import { useState } from "react";
import { NextPage } from "next";
import { navs } from "./config";
import Link from "next/link";
import { useRouter } from "next/router";
import { Button,Avatar,Dropdown,Menu, message } from "antd";
import { useStore } from 'store/index'
import { observer } from "mobx-react-lite";
import request from 'service/fetch'
import Login from "../Login";
import styles from "./index.module.scss";
import { LoginOutlined,HomeOutlined} from "@ant-design/icons";

const Navbar:NextPage = () =>{
  // 获取当前路由
  const { pathname,push } = useRouter()

  // 状态
  const [isShowLogin,setIsShowLogin] = useState(false)

  // 写文章
  const handleGoEditorPage = ()=>{
    if(userId){
      push('/editor/new')
    }else{
      message.error("请先登录")
      handleLogin()
    }
  }

  // 登录
  const handleLogin = () =>{
    // 更改登录弹框状态
    setIsShowLogin(true)
  }

  const handleClose = () =>{
    setIsShowLogin(false)
  }

  const renderDropDownMenu = () => {
    return (
      <Menu>
        <Menu.Item onClick={handleGotoPersionalPage}><HomeOutlined/>&nbsp;个人主页</Menu.Item>
        <Menu.Item onClick={handleLogout}><LoginOutlined />&nbsp;退出</Menu.Item>
      </Menu>
    )
  }
  const store = useStore()
  const {userId,avatar } = store.user.userInfo

  const  handleLogout  = () =>{
   // 退出登录
   request.post('/api/user/logout').then((res:any)=>{
    if(res?.code === 0){
      store.user.setUserInfo({})
    }
   })
  }

  const handleGotoPersionalPage = () =>{
    push(`/user/${userId}`)
  }

  return (
    <div className={styles.navbar}>
      <section className={styles.logArea}>BLOG-C</section>
      <section className={styles.linkArea}>
        {
          navs?.map((nav)=>(
            <Link key={nav?.label} href={nav?.value}>
              <a className={pathname === nav?.value ? styles.active : ""}>{nav?.label}</a>
            </Link>
          ))
        }
      </section>
      <section className={styles.operationArea}>
          <Button onClick={handleGoEditorPage}>写文章</Button>
            {
              userId ? (
                <>
                <Dropdown overlay={renderDropDownMenu()} placement='bottomLeft'>
                  <Avatar src={avatar} size={32}></Avatar>
                </Dropdown>
                </>
              ) :   <Button type="primary" onClick={handleLogin}>登录</Button>
            }
        
        </section>
      <Login isShow={isShowLogin} onClose={handleClose}/>
    </div>
  )
}

export default observer(Navbar)